#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<stack>
using namespace std;

class Solution {
public:
    int makeConnected(int n, vector<vector<int>>& connections) {
        int lineSize = connections.size();
        int sum = 0;
        for(int i = 0;i<n;i++){
            nodes[i] = i;
            parents[i] = i;
        }
        for(int i = 0;i<connections.size();++i){
            int left = connections[i][0];
            int right = connections[i][1];
            if(!isSameset(nodes[left],nodes[right])){
                unionSet(nodes[left],nodes[right]);
            }
            else{
                ++sum;
            }
        }
        //寻找有几个集合
        set<int> setNum;
        for(auto i = nodes.begin();i!=nodes.end();++i){
            setNum.insert(findFather(i->second));
        }
        if(sum<setNum.size()-1){
            return -1;
        }
        else{
            return setNum.size()-1;
        }
    }
    int findFather(int a){
        stack<int> path;
        while(parents[a]!=a){
            path.push(a);
            a = parents[a];
        }
        while(!path.empty()){
            parents[path.top()] = a;
            path.pop();
        }
        return a;
    }
    bool isSameset(int a,int b){
        return findFather(a)==findFather(b);
    }

    void unionSet(int a,int b){
        if(!isSameset(a,b)){
            int afather = findFather(a);
            int bfather = findFather(b);
            parents[afather] = bfather;
        }
    }
public:
    map<int,int> nodes;
    map<int,int> parents;
};

int main(){
    Solution S;
    vector<vector<int>> conne = {{0,1},{0,2},{0,3},{1,2}};
    cout<<S.makeConnected(6,conne)<<endl;
}